using Microsoft.EntityFrameworkCore;
using MediPlatform.Infeartructure;
using MediPlatform.Domain.Order;

namespace MediPlatform.Read.Api.Services
{
    public class RegistrationOrderDataInitializer
    {
        private readonly MyDbContext _context;
        private readonly ILogger<RegistrationOrderDataInitializer> _logger;

        public RegistrationOrderDataInitializer(MyDbContext context, ILogger<RegistrationOrderDataInitializer> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 初始化挂号订单测试数据
        /// </summary>
        public async Task InitializeAsync()
        {
            try
            {
                _logger.LogInformation("开始初始化挂号订单测试数据");

                // 检查是否已有数据
                if (await _context.RegistrationOrder.AnyAsync())
                {
                    _logger.LogInformation("挂号订单测试数据已存在，跳过初始化");
                    return;
                }

                // 确保有用户数据
                if (!await _context.User.AnyAsync())
                {
                    await CreateTestUsersAsync();
                }

                // 创建测试挂号订单
                await CreateTestRegistrationOrdersAsync();

                _logger.LogInformation("挂号订单测试数据初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化挂号订单测试数据失败");
                throw;
            }
        }

        /// <summary>
        /// 创建测试用户
        /// </summary>
        private async Task CreateTestUsersAsync()
        {
            var users = new List<User>
            {
                new User
                {
                    UserId = "U001",
                    Username = "18812341234",
                    PhoneNumber = "18812341234",
                    Email = "user1@example.com",
                    PasswordHash = "hashed_password_1",
                    Role = "patient",
                    CreatedAt = DateTime.Now.AddDays(-30),
                    UpdatedAt = DateTime.Now.AddDays(-30)
                },
                new User
                {
                    UserId = "U002",
                    Username = "18812345678",
                    PhoneNumber = "18812345678",
                    Email = "user2@example.com",
                    PasswordHash = "hashed_password_2",
                    Role = "patient",
                    CreatedAt = DateTime.Now.AddDays(-25),
                    UpdatedAt = DateTime.Now.AddDays(-25)
                },
                new User
                {
                    UserId = "U003",
                    Username = "18887654321",
                    PhoneNumber = "18887654321",
                    Email = "user3@example.com",
                    PasswordHash = "hashed_password_3",
                    Role = "patient",
                    CreatedAt = DateTime.Now.AddDays(-20),
                    UpdatedAt = DateTime.Now.AddDays(-20)
                }
            };

            await _context.User.AddRangeAsync(users);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 创建测试挂号订单
        /// </summary>
        private async Task CreateTestRegistrationOrdersAsync()
        {
            var users = await _context.User.ToListAsync();
            var random = new Random();
            var orders = new List<RegistrationOrder>();

            // 生成100条测试数据
            for (int i = 1; i <= 100; i++)
            {
                var user = users[random.Next(users.Count)];
                var status = random.Next(4); // 0-3: 待支付, 已完成, 已取消, 已退款
                var createdAt = DateTime.Now.AddDays(-random.Next(30));
                var fee = random.Next(30, 200); // 30-200元挂号费

                var order = new RegistrationOrder
                {
                    OrderNo = $"RG{DateTime.Now:yyyyMMdd}{i:D4}",
                    UserId = user.Id,
                    HospitalId = random.Next(1, 4), // 1-3
                    DepartmentId = random.Next(1, 6), // 1-5
                    DoctorId = random.Next(1, 4), // 1-3
                    ScheduleTime = createdAt.AddDays(random.Next(1, 30)),
                    Status = status,
                    Fee = fee,
                    DiscountAmount = random.Next(0, 20),
                    ActualPayment = fee - random.Next(0, 20),
                    PaymentMethod = status > 0 ? GetRandomPaymentMethod() : null,
                    PaymentTime = status > 0 ? createdAt.AddMinutes(random.Next(1, 60)) : null,
                    RefundAmount = status == 3 ? fee : null,
                    RefundTime = status == 3 ? createdAt.AddDays(random.Next(1, 7)) : null,
                    CancelReason = status == 2 ? GetRandomCancelReason() : null,
                    ExtraInfo = null,
                    CreatedAt = createdAt,
                    UpdatedAt = createdAt
                };

                orders.Add(order);
            }

            await _context.RegistrationOrder.AddRangeAsync(orders);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 获取随机支付方式
        /// </summary>
        private string GetRandomPaymentMethod()
        {
            var methods = new[] { "wechat", "alipay", "bank_card" };
            return methods[new Random().Next(methods.Length)];
        }

        /// <summary>
        /// 获取随机取消原因
        /// </summary>
        private string GetRandomCancelReason()
        {
            var reasons = new[]
            {
                "临时有事，无法就诊",
                "时间冲突，需要改期",
                "身体不适，暂时取消",
                "选择其他医院",
                "个人原因取消"
            };
            return reasons[new Random().Next(reasons.Length)];
        }
    }
} 